package javango.contrib.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javango.http.CharacterHttpResponse;
import javango.http.HttpException;

public class FreemarkerResponse extends CharacterHttpResponse {

	private final static Log log = LogFactory.getLog(FreemarkerResponse.class);
	
	protected String template;
	
	protected static Configuration cfg = null;
	static {
		// TODO probably move to guice for this.
		cfg = new Configuration();
		cfg.setTemplateLoader(new ClassTemplateLoader(FreemarkerResponse.class, "/"));
	}
	
	public void renderToWriter(Writer writer) throws HttpException {
		try {
			Template template = cfg.getTemplate(this.template);
			template.process(getContext(), writer);
		} catch (TemplateException e) {
			log.error(e,e);
			throw new HttpException(e);
		} catch (IOException e) {
			log.error(e,e);
			throw new HttpException(e);
		}
	}

	public FreemarkerResponse(String template, Map<String, Object> context) {
		this.template = template;
		setContext(context);
	}

	public String getTemplate() {
		return template;
	}

}
